package com.sdlogan.pbudget;

import java.text.DecimalFormat;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.TextView;

/**
 * The custom arrayadapter class to be used in list views
 * @author Sean
 *
 */

public class DataAdapter extends ArrayAdapter<dbPackage> {
	
	MoneyTable mt;
	Context context;
    int layoutResourceID;
    List<dbPackage> data = null;

    /**
     * Constructor for custom adapter
     * @param context  : The context view for the activities
     * @param textViewResourceId  : The resource id for the xml to be used in the listview
     * @param objects  : The data source to be displayed on the listview
     */
    
	public DataAdapter(Context context, int textViewResourceId,
			List<dbPackage> objects) {
		super(context, textViewResourceId, objects);
		this.context = context;
		this.layoutResourceID = textViewResourceId;
		this.data = objects;
		mt = new MoneyTable(getContext());
	}

	/**
	 * Returnst the list views to be displayed
	 */
	public View getView(final int position, View convertView, ViewGroup parent) {
        
        View row = convertView;
        DataHolder holder = null;

if(row == null)
{
    LayoutInflater inflater = ((Activity)context).getLayoutInflater();
    row = inflater.inflate(layoutResourceID, parent, false);
    
    holder = new DataHolder();
    holder.name = (TextView)row.findViewById(R.id.datanametype);
    holder.value = (TextView) row.findViewById(R.id.valuerow);
    holder.category = (TextView)row.findViewById(R.id.datacatdate);
    holder.occurence = (TextView) row.findViewById(R.id.occurencerow);
    holder.date = (TextView) row.findViewById(R.id.dateadded);
    
    row.setTag(holder);
}
else
{
    holder = (DataHolder)row.getTag();
}
DecimalFormat twoDForm = new DecimalFormat("#.##");
final dbPackage dbpackage = data.get(position);
holder.name.setText("Name: " + dbpackage.desc);
holder.value.setText("Value: " + twoDForm.format(dbpackage.value));
holder.category.setText("Category: " + dbpackage.category);
holder.occurence.setText("Occurence: " + dbpackage.occurence);
holder.date.setText("Date Added : " + dbpackage.day + ", " + dbpackage.month + " " + dbpackage.year);
Button b1 = (Button) row.findViewById(R.id.deletedata);
b1.setOnClickListener(new OnClickListener() {

	public void onClick(View arg0) {
		data.remove(position);
		mt.open();
		mt.deleteRowByID(dbpackage.id);
		mt.close();
		notifyDataSetChanged();
	}
});

return row;
}
	
	/**
	 * The static class to hold the variables found in the xml file
	 * @author Sean
	 *
	 */
    static class DataHolder
    {
        TextView name;
        TextView value;
        TextView category;
        TextView occurence;
        TextView date;
    }
}
